package processor;

import java.util.ArrayList;
import java.util.Iterator;

import org.slf4j.Logger;

import common.Log;

import main.run.MainThread;
import model.Student;

public class Processor extends Thread {
	private ArrayList<Student> lstStudent = new ArrayList<>(1000);
	private ArrayList<Student> lstTmp = new ArrayList<>(1000);
	private ArrayList<String> lstValue = new ArrayList<>(1000);
	private Logger logInfo = Log.logInfo();
	private Logger logErr = Log.logErr();
	@Override
	public void run() {
		try {
			while (true) {
				getData();
				parseData();
				sendData();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error(e.toString());
		}
		super.run();
	}

	private ArrayList<Student> getData() {
		try {
			synchronized (MainThread.qInput) {
				int s = MainThread.qInput.size();
				s = s / 10;
				int i = 0;
				Iterator<Student> ite = MainThread.qInput.iterator();
				while (ite.hasNext()) {
					if (i > s) {
						break;
					}
					Student student = ite.next();
					lstStudent.add(student);
					lstTmp.add(student);
					i++;
				}
				for (int j = 0; j < lstTmp.size(); j++) {
					MainThread.qInput.remove(lstTmp.get(j));
					logInfo.info("Sap xu ly: " + lstTmp.get(j).toString());
				}
//				MainThread.qInput.wait();
				if (lstStudent.size() != 0) {
					MainThread.qInput.notifyAll();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error(e.toString());
		}
		return lstStudent;
	}

	private void parseData() {
		for (int i = 0; i < lstStudent.size(); i++) {
			Student student = lstStudent.get(i);
			String value = student.toString();
			lstValue.add(value);
		}
		lstStudent.clear();
	}

	private void sendData() {
		try {
			synchronized (MainThread.qOutput) {
				for (int i = 0; i < lstValue.size(); i++) {
					String value = lstValue.get(i);
					MainThread.qOutput.add(value);
					logInfo.info("Da xu ly: " + value);
				}
				lstValue.clear();
//				MainThread.qInput.wait();
				MainThread.qOutput.notifyAll();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logErr.error(e.toString());
		}
	}

}
